<?php

namespace app\index\controller;

use think\Controller;
use think\Request;

use app\index\model\Payorder;
use app\index\model\Qrcode;
use app\index\model\Express;
use app\index\model\Member;

use \payment\Weixin;

class Payment extends Controller
{
    public function index(){
        return redirect('/index/payment/placeorder');
    }
    /**
     * 新建订单
     */
    public function placeOrder(){
        $wx = new Weixin;
        $info = input('post.');
        $orderNo = $info['orderNum'];
        $des = $info['describe'];
        if(isset($info['money'])){
            $price = $info['money'];
        }else{
            return json(mesg(-1, '请输入充值金额'));
            // $kd = new Express();
            // $kdcodes = $kd->getColumn('billcode');
            // cache($orderNo, json_encode($kdcodes), 600);
            // $price = count($kdcodes);
        }
        $res = $wx->unifiedOrder($des, $orderNo, $price, session('openid'));
        if($res){
            $order = new Payorder();
            $data = [
                'uid'         => session('user.id'),
                'trade_no'    => $orderNo,
                'des'         => $des,
                'price'       => $price,
                'trade_type'  => 'JSAPI',
            ];
            $dataRes = $order->newOrder($data);

            if(!$dataRes) return json(mesg(-1, 'fail'));
            //签名数据
            $config = [
                'appId'     => $res['appid'],     //公众号名称，由商户传入  
                'timeStamp' => strval(time()),        //时间戳，自1970年以来的秒数     
                'nonceStr'  => getNonceStr(), //随机串     
                'package'   => 'prepay_id=' . $res['prepay_id'],     
                'signType'  => 'MD5',         //微信签名方式
            ];
            $config['paySign'] = $wx->MakeSign($config); //微信签名 
            return json(mesg(0, 'success', $config));
        }else{
            return(mesg(-1,'新建订单失败'));
        }
    }

    //用户购买二维码生成
    public function paySuccess(){
        $orderNo = input('orderNum', 0);
        
        $order = Payorder::where('trade_no', $orderNo)->find();
        if(!empty($order)){
            $qr = new Qrcode();
            if($order->status == 1){
                $qr->insertQr($orderNo);
                if($order->trade_type == 'Balance'){
                    Member::updateBalance(session('user.id'), -$order->price, $order->des);
                }
                Member::updatePoint(session('user.id'), $order->des, $order->price);
                return json(['code'=>0, 'msg'=>'支付成功']);
            }else{
                $wx = new Weixin();
                $res = $wx->queryOrder($orderNo);
                if($res){
                    $order->status = 1;
                    $order->save();
                    Member::updateBalance(session('user.id'), $order->price, $order->des);
                    $kd = new Express();
                    $kdcodes = $kd->getColumn('billcode');
                    cache($orderNo, json_encode($kdcodes), 600);
                    $price = count($kdcodes);
                    if($price > Member::where('memb_id', session('user.id'))->value('memb_balance')){
                        return json(mesg(601, '金额不足，无法生成二维码'));
                    }
                    $qr->insertQr($orderNo);
                    Member::updatePoint(session('user.id'), '二维码取件', $price);
                    return json(['code'=>0, 'msg'=>'成功生成二维码']);
                }
            }
            return json(['code'=>-3, 'msg'=>'未支付']);
        }
    }

    //微信关闭订单
    public function closeOrder(){
        $orderNo = input('orderNo');
        $order = Payorder::where('trade_no', $orderNo)->find();
        if(!empty($order) && $order->status == 0){
            $wx = new Weixin();
            $res = $wx->closeOrder($orderNo);
            if($res){
                $order->status = 3;
                $order->save();
                return json(mesg(0, 'success'));
            }
        }
        return json(mesg(-2, 'fail'));
    }

}
